<template>
    <div class="hc-answer-sheet-canvas" :style="boxStyle">
        <div :style="styleConbine()">
            <div v-for="(page, index) in pagesInfo">
                <canvas
                        :key="index"
                        :id="page.id"
                        :style="page.backGround"
                        :width="width"
                        :height="height"
                ></canvas>
            </div>
        </div>
    </div>
</template>

<script>
  import {Utils} from "../utils/Utils";
  import {PaperConfig} from '../config/PaperConfig';
  import uuid from "uuid";

  let width = 700;
  let height = width * (297 / 210);
  let cof = width / 210;

  let countXy = function ({x, y}) {
    let scale = height / 297;

    return {x: x * scale, y: y * scale};
  };
  let randomStr = uuid().toString();
  export default {
    name: "StrokeView",
    data() {
      return {
        pagesInfo: [],
        height,
        width,
        boxStyle: {height: "min-content"},
        lastCanvas: []
      };
    },
    watch: {
      strokeData() {
        try {
          this.doStroke();
        } catch (e) {
          // console.log(e)
        }
      }
    },
    computed: {
      canvasBoxStyle() {
        return {
          height: ((297 - 15) * cof).toFixed(2) + 'px',
          overflow: 'hidden'
        }
      },
      viewArea() {
        let area = {};
        try {
          area = JSON.parse(this.questionAnswerArea);
          // console.log(area);
          return {area, state: true};
        } catch (e) {
          return {state: false};
        }
      }
    },
    methods: {
      styleConbine() {
        if (this.viewArea.state) {
          let temp = {
            overflow: "hidden",
            height:
              (((((this.viewArea.area.d.page === this.viewArea.area.a.page) ?
                  (this.viewArea.area.d.y - this.viewArea.area.a.y) : (297 - this.viewArea.area.a.y + this.viewArea.area.d.y))
                  + ((this.viewArea.area.d.page > this.viewArea.area.a.page) ? (this.viewArea.area.d.page - this.viewArea.area.a.page - 1) : 0) * 297) * cof+ 25).toFixed(2)
              )
              // - (this.viewArea.area.d.page - this.viewArea.area.a.page) * 100
              // + 4 + 6*(this.setWidth-800)/400*(this.viewArea.area.d.page - this.viewArea.area.a.page)
              + "px",
            display: "flex",
            "flex-direction": "column"
          };
          this.boxStyle = Object.assign(this.boxStyle, temp);
        }
        return {
          "margin-top": `${
            ((this.viewArea.state && this.viewArea.area.a.page && this.pagesInfo[0] && this.pagesInfo[0].page)
              ? -(
                this.viewArea.area.a.y * cof +
                (297 * cof * (this.viewArea.area.a.page - this.pagesInfo[0].page)) -
                12 - 5 * (this.viewArea.area.a.page - this.pagesInfo[0].page)
                // 185 / PaperConfig.height * 297 * cof -
                // (15 * cof * (this.viewArea.area.a.page - this.pagesInfo[0].page-1))
              )
              : 0).toFixed(2)
            }px`,
          // "margin-left": `${
          //     this.viewArea.state ? -(this.viewArea.area.a.x * cof) : 0
          //     }px`
        };
      },
      doStroke() {
        /** 渲染画板 **/
        let strokes, teacherStrokes;
        this.lastCanvas.map((canvas) => {
          canvas.clearRect(0, 0, this.width, this.height);
        });
        try {
          strokes = Utils.handleAnswerData(this.strokeData);
          teacherStrokes = Utils.handleAnswerData(this.teacherStrokeData);
        } catch (e) {

        }
        /***  页码  */
        this.lastCanvas = [];
        let pagesInfo = [];
        let idx = 0;
        for (let page of this.pages) {
          let backGround = {};
          if (this.imgs[idx]) {
            backGround["background"] = `url(${this.imgs[idx++]})`;
            backGround["background-size"] = "contain";
            backGround['margin'] = '0 auto';
            // backGround['marginTop'] = -PaperConfig.paddingTop / PaperConfig.height * 297 * cof + 'px';
          }
          pagesInfo.push({id: `${page}-${randomStr}`, page, backGround});
        }
        this.pagesInfo = pagesInfo;
        this.$nextTick(() => {
          let lastIdx = -1;
          for (let i = 0; i < pagesInfo.length; i++) {
            let pageInfo = pagesInfo[i];
            let cav;
            try {
              cav = document.getElementById(pageInfo.id).getContext("2d");
            } catch (e) {
              // console.error(e)
              continue
            }
            this.lastCanvas.push(cav);

            cav.strokeStyle = "black";
            cav.beginPath();
            let dots, tDots;
            try {
              dots = strokes[pageInfo.page];
            } catch (e) {
              return
            }
            if (teacherStrokes) {
              tDots = teacherStrokes[pageInfo.page];
            }
            // console.log(teacherStrokes, tDots);
            if (!dots) {
              continue;
            }

            for (let j in dots) {
              let timeDots = dots[j];
              for (let k = 0; k < timeDots.length; k++) {
                let dot = timeDots[k];
                let {x, y} = countXy({x: dot.x, y: dot.y});

                if (dot.idx != lastIdx) {
                  cav.moveTo(x, y);
                  lastIdx = dot.idx;
                } else {
                  cav.lineTo(x, y);
                }
              }
              // debugger;
            }
            cav.stroke();
            cav.closePath();
            if (!tDots) {
              continue;
            }


            cav.strokeStyle = "red";
            cav.beginPath();
            for (let j in tDots) {
              let timeDots = tDots[j];
              for (let k = 0; k < timeDots.length; k++) {
                let dot = timeDots[k];
                let {x, y} = countXy({x: dot.x, y: dot.y});

                if (dot.idx != lastIdx) {
                  cav.moveTo(x, y);
                  lastIdx = dot.idx;
                } else {
                  cav.lineTo(x, y);
                }
              }
              // debugger;
            }
            cav.stroke();
            cav.closePath();
          }
        });
      }
    },
    created() {
      width = this.width = this.setWidth;
      height = this.height = width * (297 / 210);
      cof = width / 210;
      try {
        this.doStroke();
      } catch (e) {
        // console.log(e)
      }
    },
    props: {
      strokeData: {
        type: String,
        default: function () {
          return ''
        }
      },
      teacherStrokeData: {
        type: String,
        default: function () {
          return ''
        }
      },
      pages: {
        type: Array,
        default: function () {
          return []
        }
      },
      imgs: {
        type: Array,
        default: function () {
          return []
        }
      },
      questionAnswerArea: {
        type: String,
        default: function () {
          return ''
        }
      },
      setWidth: {
        type: Number,
        default: function () {
          return 700
        }
      }
    }
  };
</script>

<style scoped>
</style>
